import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:village_android/component/image_tile.dart';
import 'package:village_android/component/jd_button.dart';
import 'package:village_android/config/contants.dart';
import 'package:village_android/model/user_model.dart';
import 'package:village_android/utils/common_utils.dart';
import 'package:village_android/utils/http_utlis.dart';
import 'package:village_android/utils/store_utils.dart';
import 'dart:convert' as convert;
import 'package:image_picker/image_picker.dart';

class ProfileDetailPage extends StatefulWidget {
  @override
  _ProfileDetailPageState createState() => new _ProfileDetailPageState();
}

class _ProfileDetailPageState extends State<ProfileDetailPage> {
  final _formKey = GlobalKey<FormState>();

  //获取本地用户
  UserModel userModel = CommonUtils.getLocalUserInfo();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('个人信息修改'),
        ),
        bottomNavigationBar: initBottom(),
        body: Container(
          padding: EdgeInsets.all(20),
          child: Form(
            key: _formKey,
            child: ListView(
              children: <Widget>[
                SizedBox(height: 10.0),
                ImageTile(
                    leading: userModel.avatar,
                    title: "头像",
                    action: () {
                      _openGallery("avatar");
                    }),
                SizedBox(height: 10.0),
                initAddress(),
                SizedBox(height: 10.0),
                initQQ(),
                SizedBox(height: 10.0),
                initWechat(),
                SizedBox(height: 10.0),
                initVillageJob(),
                SizedBox(height: 10.0),
                Text(
                  "身份证上传【正/反面】",
                  style: TextStyle(color: Colors.red),
                ),
                SizedBox(height: 10.0),
                Row(
                  children: <Widget>[
                    Padding(padding: EdgeInsets.only(left: 10)),
                    Expanded(
                      child: initUpCard(),
                    ),
                    Padding(padding: EdgeInsets.only(left: 15)),
                    Expanded(
                      child: initDownCard(),
                    ),
                    Padding(padding: EdgeInsets.only(right: 10)),
                  ],
                ),
                SizedBox(height: 10.0),
              ],
            ),
          ),
        ));
  }

  TextFormField initAddress() {
    return TextFormField(
      initialValue: userModel.address,
      onSaved: (String value) => userModel.address = value,
//      maxLength: 11,
      decoration: InputDecoration(labelText: '地址'),
    );
  }

  TextFormField initQQ() {
    return TextFormField(
      initialValue: userModel.qq,
      onSaved: (String value) => userModel.qq = value,
//      maxLength: 11,
      decoration: InputDecoration(labelText: 'qq'),
    );
  }

  TextFormField initWechat() {
    return TextFormField(
      initialValue: userModel.wechat,
      onSaved: (String value) => userModel.wechat = value,
//      maxLength: 11,
      decoration: InputDecoration(labelText: '微信'),
    );
  }

  TextFormField initVillageJob() {
    return TextFormField(
      initialValue: userModel.villageJob,
      onSaved: (String value) => userModel.villageJob = value,
//      maxLength: 11,
      decoration: InputDecoration(labelText: '村务职务'),
    );
  }
  Widget initUpCard() {
    return GestureDetector(
        child: Container(
//          color: Colors.black12,
          height: 120,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: NetworkImage(kImageHost + 'upload_asset.png'),
              fit: BoxFit.contain,
            ),
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(10),
            child: Image.network(
              userModel.upcardURL,
              height: 100,
              width: 100,
              fit: BoxFit.fill,
            ),
          ),
        ),
        onTap: (() {
          _openGallery("upcardURL");
        }));
  }
  Widget initDownCard() {
    return GestureDetector(
        child: Container(
//          color: Colors.black12,
          height: 120,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: NetworkImage(kImageHost + 'upload_asset.png'),
              fit: BoxFit.contain,
            ),
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(10),
            child: Image.network(
              userModel.downcardURL,
              height: 100,
              width: 100,
              fit: BoxFit.fill,
            ),
          ),
        ),
        onTap: (() {
          _openGallery("downcardURL");
        }));
  }

  // 上传图片
  _openGallery(field) async {
    var imgfile = await ImagePicker.pickImage(source: ImageSource.gallery,imageQuality: 10);
    String path = imgfile.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    FormData formData =
        new FormData.from({"file": new UploadFileInfo(new File(path), name)});

    HttpUtils.postForm("/api/file/upload", formData: formData,context: context, success: (data) {
      CommonUtils.showToast(context, "上传成功");
      setState(() {
        var src = data["src"];
        if (field == "avatar") {
          userModel.avatar = src;
        } else if (field == "upcardURL") {
          userModel.upcardURL = src;
        }else if (field == "downcardURL") {
          userModel.downcardURL = src;
        }
      });
    }, error: (errorMsg) {
      CommonUtils.showToast(context, errorMsg);
    });
  }

  Widget initBottom() {
    return BottomAppBar(
        child: Row(
          children: <Widget>[
            Expanded(
                child: JdButton(
                  callBack: () {
                    //CommonUtils.showToast(context, '登录');
                    //CommonUtils.showToast(context, '登录');
                    if (_formKey.currentState.validate()) {
                      _formKey.currentState.save();
                    }
                    toDone();
                  },
                  text: "确定",
                  color: Colors.red,
                )),
          ],
        ));
  }


  Future toDone() async {
    FormData formData = new FormData.from(userModel.toJson());

    HttpUtils.postForm("/mgr/edit", formData: formData, success: (data) {
      CommonUtils.showToast(context, "修改成功");
      String jsonString = convert.jsonEncode(userModel);
      SharedPreferenceUtil.save(SharedPreferenceUtil.KEY_USERMODEL, jsonString);
      new Future.delayed(
          const Duration(seconds: 1), () => {Navigator.of(context).pop()});
    }, error: (errorMsg) {
      CommonUtils.showToast(context, errorMsg);
    });
  }
}
